<template>
  <div class="record-cite" v-loading="loading">
    <div v-if="resetLoad" id="pdfDom" ref="print">
      <el-container class="record-edit-form-container">
        <el-aside width="278px" class="record-edit-form-container_aside">
          <ElnTemplateSide
            ref="ElnTemplateSide"
            :form-data="formData"
            :page-view-mode="pageViewMode2"
            :detection-state="detectionState"
          />
        </el-aside>
        <el-main class="record-edit-form-container_main">
          <div
            v-for="item in targetList"
            :key="item.id"
            class="target-card-item"
            :style="{ width: item.span === 12 ? '50%' : '100%' }"
          >
            <component
              :is="item.name"
              :ref="item.name"
              class="card-item"
              :params="item"
              :page-view-mode="pageViewMode2"
              :is-create="operateType === 0"
              @tableLoadHandle="tableLoadHandle"
            ></component>
          </div>
        </el-main>
      </el-container>
      <div class="dialog-footer" align="center">
        <el-button type="primary" @click="save(1)">提交</el-button>
        <el-button v-if="!sampleState" type="primary" @click="save(0)"
          >暂存</el-button
        >
      </div>
    </div>
  </div>
</template>
<script>
import { update, create } from "../../../api/Eln/ExperimentTemplateRecord";
import { getSingleList } from "../../../api/Eln/ExperimentTemplate.js";
import { getUserListNoPage } from "../../../api/Permission/user.js";
import { deepClone } from "../../../utils";
import { leaveTime } from "@/utils/moment";
import _ from "lodash";
// 引入组件
import ElnTemplateSide from "../Components/ElnTemplateSide.vue";
const allComponents = require.context(
  "../../../components/BaseControl",
  true,
  /\.vue$/
);
const res_components = {};
allComponents.keys().forEach((item) => {
  const comp = allComponents(item);
  const name = comp.default.name;
  res_components[name] = comp.default;
});
export default {
  name: "ExperimentTemplateRecordEdit",
  components: { ...res_components, ElnTemplateSide },
  data() {
    return {
      dialogVisible: false,
      resetLoad: false,
      loading: false,
      customClass: "panna-dialog_big",
      pageViewMode2: "runtime", // runtime 运行时 design 设计时 pageview 预览  print 打印
      copyPageViewMode: "",
      formLabelWidth: "70px",

      operateType: 0,

      reviewerList: [],
      zipPromise: [],
      targetList: [],
      defaultValueJSONType: [
        "Radio",
        "Select",
        "Checkbox",
        "MultipleSelect",
        "Table",
        "DatePicker",
      ],
      valueJSONType: [
        "Radio",
        "Select",
        "Checkbox",
        "MultipleSelect",
        "Table",
        "Image",
      ],
      formData: {
        experimentNumber: "",
        articleNumber: "",
        // sampleCategoryName: "",
        detectionItemName: "",
        creatorTime: "",
        creatorName: [],
      },
      errorMsg: {
        experimentNumber: "",
        articleNumber: "",
        // sampleCategoryName: "",
        detectionItemName: "",
        creatorTime: "",
        creatorName: "",
      },
      searchUserLoading: false,
      userList: [],
      // 样品登记那里传过来变为true
      sampleState: false,
      // 是否显示检测项目结果设置列表
      detectionState: true,
    };
  },
  computed: {
    pdfCreatorName() {
      return (
        this.formData?.templateContentDto.leftData.find(
          (x) => x.code === "creatorName"
        )?.value || ""
      );
    },
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      if (this.$route.query.sampleState != null) {
        this.sampleState = this.$route.query.sampleState;
      }
      const id = this.$route.query.id;
      this.detectionState =
        this.$route.query.state === "false"
          ? false
          : Boolean(this.$route.query.state);

      getSingleList({ Id: id }).then((res) => {
        Object.assign(this.formData, res.data);
        this.formData.experimentNumber = this.formData.templateCode;
        if (!res.data.templateContentDto) {
          this.resetLoad = false;
          return;
        }
        const JPTemplate = (this.sendTemplate = res.data.templateContentDto);
        this.leftData = JPTemplate.leftData;
        // let isExisTable = false;
        this.targetList = JPTemplate.centerData.filter((x) => {
          if (x.controlType === "Table") {
            x.required = false;
            // if (isExisTable) return false;
            // else {
            //   isExisTable = true;
            //   return true;
            // }
          }
          return x && x.controlType !== "Title";
        });
        this.targetList.forEach((item) => {
          item.placeholder = "";
          item.name = `Control${item.controlType}`;
          if (item.value && this.valueJSONType.includes(item.controlType)) {
            item.value = JSON.parse(item.value);
          }
          if (
            item.defaultValue &&
            this.defaultValueJSONType.includes(item.controlType)
          ) {
            item.defaultValue = JSON.parse(item.defaultValue);
          }
        });
        this.resetLoad = true;
      });
    },
    save: _.throttle(function (type) {
      const runFn = async () => {
        const saveList = new Array(this.targetList.length).fill(null);
        let allControlSuccess = true;
        const promiseTable = [];
        for (const i in this.$refs) {
          if (i === "formData") continue;
          const tempRef = this.$refs[i];
          if (!Array.isArray(tempRef) || !tempRef.length) continue;
          tempRef.forEach((ref) => {
            if (ref.validate instanceof Function) {
              const refData = ref.validate();
              if (refData instanceof Promise) {
                promiseTable.push(refData);
                return;
              }
              const { controlValue, validateError } = deepClone(refData);
              validateError === true && (allControlSuccess = false);
              // 删除多余的参数
              delete controlValue.name;
              // 修改特定控件value&defaultValue数据格式
              controlValue.data = controlValue.data.filter(
                (x) => x.label !== ""
              );
              // 格式化特殊控件的value以及defaultValue值
              controlValue.value &&
                this.valueJSONType.includes(controlValue.controlType) &&
                (controlValue.value = JSON.stringify(controlValue.value));
              controlValue.defaultValue &&
                this.defaultValueJSONType.includes(controlValue.controlType) &&
                (controlValue.defaultValue = JSON.stringify(
                  controlValue.defaultValue
                ));
              const currentIdx = this.targetList.findIndex(
                (x) => x.id === controlValue.id
              );
              saveList.splice(currentIdx, 1, controlValue);
            }
          });
        }
        if (!allControlSuccess) return;
        // 处理table的异步数据问题
        if (promiseTable.length) {
          const tableData = await Promise.all(promiseTable);
          tableData.forEach((x) => {
            const { controlValue } = deepClone(x);
            const currentIdx = this.targetList.findIndex(
              (v) => v.id === controlValue.id
            );
            controlValue.value &&
              (controlValue.value = JSON.stringify(controlValue.value));
            controlValue.defaultValue &&
              (controlValue.defaultValue = JSON.stringify(
                controlValue.defaultValue
              ));
            saveList.splice(currentIdx, 1, controlValue);
          });
        }
        const operateTypeFn = this.operateType === 0 ? create : update;
        const params = deepClone(this.formData);
        params.templateId = params.id;
        delete params.id;
        params.source = 1;
        params.entrustTaskId = this.entrustTaskId;
        params.submitStatus = type;
        params.creatorId = this.$store.getters.currentUserId;
        params.detectionTime = this.formData.createTime;
        params.testerId = this.formData.creatorName;
        const leftData = params.templateContentDto.leftData;
        leftData.forEach((x) => {
          try {
            switch (x.code) {
              case "creatorTime":
                x.value = leaveTime(this.formData[x.code]);
                break;
              case "creatorName":
                x.value = this.formData[x.code].join(",");
                break;
              default:
                x.value = this.formData[x.code];
                break;
            }
          } catch (error) {
            console.log(error);
          }
        });
        params.templateContentDto = {
          leftData: leftData,
          centerData: saveList,
        };
        if (this.sampleState) {
          localStorage.setItem("closedPageValue", JSON.stringify(params));
          window.opener = null;
          window.open("about:blank", "_top").close();
        } else {
          this.loading = true;
          operateTypeFn(params)
            .then((res) => {
              this.loading = false;
              if (res.code !== 200) return;
              // 关闭当前标签页
              window.opener = null;
              window.open("about:blank", "_top").close();
            })
            .catch(() => {
              this.loading = false;
            });
        }
      };
      this.$refs.ElnTemplateSide.validate().then((val) => {
        if (!val) return;
        runFn();
      });
    }, 5000),
    // 判断当前表单是否存在表格控件
    judgeTableExist() {
      const currentFormData = this.formData;
      if (!currentFormData) return;
      const exit = currentFormData.templateContentDto?.centerData?.some(
        (x) => x.controlType === "Table"
      );
      !exit && this.beforeDownLoadPdf();
    },
    // 表格渲染完成
    tableLoadHandle() {
      this.autoDownZip && this.$nextTick(this.beforeDownLoadPdf);
    },

    // 获取检测人信息(签名)
    getUser(name = "") {
      return new Promise((resolve) => {
        getUserListNoPage({ name }).then((res) => {
          resolve(res);
        });
      });
    },
  },
};
</script>

<style lang="scss">
.Eln_flex {
  display: flex;
  align-items: center;
  align-content: flex-start;
  justify-content: space-between;
  flex-wrap: wrap;
}

.record-cite {
  height: 100%;

  #pdfDom {
    height: 100%;
    display: flex;
    flex-direction: column;

    .record-edit-form-container {
      min-height: 0;

      .record-edit-form-container_aside {
        box-sizing: border-box;
        padding: 24px;
        background-color: #ecf0f7;
        overflow: hidden;
        overflow-y: auto;
      }

      .record-edit-form-container_main {
        @extend .Eln_flex;
        padding: 0 16px;
        min-height: 600px;
        padding-bottom: 20px;
        @extend .Eln_flex;
        justify-content: flex-start;
        overflow: auto;

        & > .target-card-item {
          margin-top: 18px;

          // 各控件基础样式
          .control {
            display: flex;
            align-items: center;
            box-sizing: border-box;

            &.flex-start {
              align-items: flex-start;
            }

            &.image {
              align-items: flex-start;

              & > .control-title {
                margin-top: 6px;
              }

              & > .control-operate {
                margin-top: 4px;
              }
            }

            & > * {
              flex-shrink: 0;
            }

            & > .control-title {
              // width: 80px;
              height: 16px;
              font-size: 12px;
              font-family: "Microsoft YaHei";
              color: #666666;
              line-height: 16px;
              display: flex;
              align-items: center;
              justify-content: flex-end;

              & > .title-icon {
                color: red;
                padding-right: 3px;
              }

              & > .title-label {
                text-align: right;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }
            }

            .control-content {
              flex: 1;
              margin-right: 52px;
              margin-left: 10px;
              position: relative;

              &.validateError {
                .el-input > .el-input__inner,
                .el-textarea > .el-textarea__inner {
                  border-color: #ff4949;
                }
              }

              .control-validate-error {
                position: absolute;
                top: 100%;
                left: 0;
                padding-top: 2px;
                color: #ff4949;
                font-size: 12px;
                line-height: 1;
              }
            }
          }
        }
      }
    }

    .dialog-footer {
      margin: 20px 0;
      .footer-title {
        display: inline-block;
        width: 100%;
        box-sizing: border-box;
        padding: 13px 16px;
        line-height: 14px;
        font-size: 14px;
        text-align: left;
        background-color: #f1f8ff;
      }

      ul {
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;

        & > li {
          width: calc(100% / 3);
          box-sizing: border-box;
          padding: 10px 16px;
          text-align: left;
          display: flex;
          align-items: center;

          &.jianceren {
            span {
              line-height: 22px;
            }
            & > .jianceren-nodename {
              flex-shrink: 0;
            }
          }

          & > .verify-item {
            box-sizing: border-box;

            & > span {
              display: inline-block;
              white-space: pre-wrap;
              word-break: break-all;
              max-width: 112px;
            }
          }

          & > .verify-account {
            flex: 1 0;
            overflow: hidden;

            span {
              display: block;
            }
          }
        }
      }
    }
  }
}
</style>
